import { defineStore } from "pinia";

import { ipcApiRoute } from "@/api/main";
import { ipc } from "@/utils/ipcRenderer";
import { ElMessage, ElMessageBox } from "element-plus";
import { getTaskName } from "@/utils/index";
let p = {
  type: "active",
  offset: 0,
  num: 20,
};

export const useTaskStore = defineStore("task", {
  // persist: true,
  state: () => ({
    // 新增种子
    addTaskTorrents: [],
    activeTaskList: [],
    waitingTaskList: [],
    stoppedTaskList: [],
    intervalCode: null,
    selectTaskGidList: [],
  }),
  getters: {},
  actions: {
    setSelectTaskGidList(val) {
      this.selectTaskGidList = val;
    },
    setTaskTorrentHandle(val) {
      console.log("setTaskTorrentHandle");
      this.addTaskTorrents = [...val];
      console.log(this.addTaskTorrents);
    },
    /**
     * 按照状态获取任务数据
     * @param {*} type
     */
    getTaskList(
      params = {
        type: "active",
        offset: 0,
        num: 20,
      }
    ) {
      ipc
        .invoke(ipcApiRoute.getTaskList, JSON.parse(JSON.stringify(params)))
        .then((res) => {
          let name = params.type + "TaskList";
          this[name] = res;
          console.log(
            "getTaskList",
            res,
            params.type === "active",
            this.intervalCode
          );
          if (params.type === "active") {
            let activeStatus = res.some((item) => {
              return item.status === "active";
            });
            if (!activeStatus) {
              this.clearActiveTaskInfoInterval();
            }
            if (activeStatus && this.intervalCode == null) {
              this.getActiveTaskInfoInterval({ ...params });
            }
          }
        });
    },
    getActiveTaskInfoInterval(params) {
      let that = this;
      this.clearActiveTaskInfoInterval();

      this.intervalCode = setTimeout(() => {
        // 获取进度
        // console.log("intervalCode", params);
        // 获取列表
        that.getTaskList({ ...params });
        that.getActiveTaskInfoInterval({ ...params });
      }, 1000);
    },
    clearActiveTaskInfoInterval() {
      if (this.intervalCode) {
        clearTimeout(this.intervalCode);
      }
      this.intervalCode = null;
    },

    stopAll(params) {
      ipc.invoke(ipcApiRoute.stopAllTask).then((res) => {
        ElMessage({
          message: "全部暂停成功",
          type: "success",
        });
        this.clearActiveTaskInfoInterval();
        setTimeout(() => {
          this.getTaskList({ ...params });
        }, 1000);
      });
    },

    startAll(params) {
      ipc.invoke(ipcApiRoute.startAllTask).then((res) => {
        ElMessage({
          message: "全部开始成功",
          type: "success",
        });
        this.getTaskList({ ...params });
        this.getActiveTaskInfoInterval();
      });
    },

    stopOne(params) {
      ipc.invoke(ipcApiRoute.stopByGid, params).then((res) => {
        ElMessage({
          message: "暂停成功",
          type: "success",
        });
        this.getTaskList();
      });
    },

    startOne(params) {
      ipc.invoke(ipcApiRoute.startByGid, params).then((res) => {
        ElMessage({
          message: "开始成功",
          type: "success",
        });
        this.getTaskList();
      });
    },
    /**
     *
     * @param {{gids: []}} params
     */
    deleteTasks(params) {
      if (this.selectTaskGidList.length > 0) {
        ElMessageBox.confirm(
          `确认删除${this.selectTaskGidList.length}项嘛？`,
          "提示",
          {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
          }
        ).then(() => {
          ipc
            .invoke(ipcApiRoute.removeTaskByGids, {
              gids: [...this.selectTaskGidList],
            })
            .then((res) => {
              ElMessage({
                message: "删除成功",
                type: "success",
              });
              this.getTaskList(params);
            });
        });
      }
    },

    deleteTask(params, item) {
      ElMessageBox.confirm(`确认删除${getTaskName(item)}嘛？`, "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      }).then(() => {
        ipc
          .invoke(ipcApiRoute.removeTaskByGids, {
            gids: [item.gid],
          })
          .then((res) => {
            ElMessage({
              message: "删除成功",
              type: "success",
            });
            this.getTaskList(params);
          });
      });
    },
    openDirectory(id) {
      ipc
        .invoke(ipcApiRoute.openDirectory, {
          id,
        })
        .then((res) => {
          ElMessage({
            message: "打开成功",
            type: "success",
          });
        });
    },
  },
});
